var salt = sessionStorage.getItem('usersalt');
layui.config({
	base: '../../../js/',
})
layui.use(['form', 'layer', 'laydate', 'table', 'multiSelect'], function() {
	var form = layui.form,
		layer = parent.layer === undefined ? layui.layer : top.layer,
		$ = layui.jquery,
		laydate = layui.laydate,
		formSelects = layui.formSelects,
		table = layui.table;

	/*验证登录*/
	if(!sessionStorage.getItem('username')) {
		layer.msg('请先登录');
		setTimeout("top.location.href='../../../index.html'", 1000);
	}

	/*时间选择器*/
	laydate.render({
		elem: '#statdate',
		trigger: 'click'
	});

	laydate.render({
		elem: '#enddate',
		trigger: 'click'
	});

	/*筛选*/
	$('#seleCheck').on('click', function() {
		getDangerList();
	});

	/*搜索*/
	$('#findscri').on('click', function() {
		var inptext = $('#inptext').val();
		var box = /\s/g;
		var param = inptext.replace(box, '');
		getDangerList(param);
	});
	var company;
	/*取出所有的单位*/
	function getAllDanwei() {
		$.ajax({
			url: url + 'baseEnt/getAllEnt',
			dataType: 'json',
			async: false,
			type: "POST",
			data: {},
			success: function(data) {
				$('#danwei').empty();
				if(data.code == 0) {
					var list = data.data;
					company = list;
				}

			},
			error: function(error) {
				console.log("获取失败");
			}
		});
	}

	getAllDanwei();

	var setting = {
		check: {
			enable: true
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			onCheck: zTreeOnCheck
		}
	};
	var zNodes = company;
	$.fn.zTree.init($("#danwei"), setting, zNodes);

	function getSydwVal() {
		var treeArr = [];
		var treeObj = $.fn.zTree.getZTreeObj("danwei");
		var nodes = treeObj.getCheckedNodes(true);
		for(var i = 0; i < nodes.length; i++) {
			treeArr.push(nodes[i].id); //获取选中节点的值
		}
		return treeArr;
	}
	$('#resclas').click(function() {
		$("body").trigger("click");
		$('#danwei').show();
	});

	function zTreeOnCheck(event, treeId, treeNode) {
		var nval = "";
		var treeObj = $.fn.zTree.getZTreeObj("danwei");
		var nodes = treeObj.getCheckedNodes(true);
		for(var i = 0; i < nodes.length; i++) {
			nval += nodes[i].name + ",";
		}
		$('#resclas').val(nval.substr(0, nval.length - 1));
	};
	/*------------tree.end------------*/

	var tableIns;
	//危险源列表
	function getDangerList(searchText) {
		var sydwArr = getSydwVal();
		if(!searchText) {
			searchText = null;
		}

		var types = [];
		var obj_type = document.getElementById("type");
		for(var i = 0; i < obj_type.options.length; i++) {
			if(obj_type.options[i].selected) {
				types.push(obj_type.options[i].value); // 收集选中项			
			}
		}

		var risks = [];
		var obj_risk = document.getElementById("risk");
		for(var i = 0; i < obj_risk.options.length; i++) {
			if(obj_risk.options[i].selected) {
				risks.push(obj_risk.options[i].value); // 收集选中项			
			}
		}

		var factors = [];
		var obj_factor = document.getElementById("factor");
		for(var i = 0; i < obj_factor.options.length; i++) {
			if(obj_factor.options[i].selected) {
				factors.push(obj_factor.options[i].value); // 收集选中项			
			}
		}

		tableIns = table.render({
			elem: '#dangerList',
			method: 'post',
			url: url + 'dangerList/getPage',
			height: 'full-115',
			where: {
				Token: salt, //用户码
				name: $('#inptext').val(), //搜索文本框内容
				entId: sydwArr.toString(), //适用单位ids
				type: types.toString(), //检查分类
				risk: risks.toString(), //作业风险
				factor: factors.toString() //风险因素

			},
			cellMinWidth: 95,
			page: true,
			id: "dangerListTable",
			cols: [
				[{
						type: "numbers",
						width: 50,
						title: "序号",
					},
					{
						type: "checkbox",
						width: 50
					},
					{
						field: 'type',
						title: '类别',
						align: 'center',
						templet: function(p) {
							if(p.type == null) {
								return "<div></div>";
							} else if(p.type == '0') {
								return "<div onclick=showDetail('" + p.id + "')>" + p.typeName + "</div>";
							} else if(p.type == '1') {
								return "<div onclick=showDetail('" + p.id + "')>危险物料</div>";
							} else if(p.type == '2') {
								return "<div onclick=showDetail('" + p.id + "')>环境因素</div>";
							}

						}
					},
					{
						field: 'name',
						title: '名称',
						align: 'center',
						templet: function(p) {
							if(p.name) {
								return "<div class='riskName' riskId='" + p.id + "' onclick=showDetail('" + p.id + "')>" + p.name + "</div>";
							} else {
								return "<div class='riskName' riskId='" + p.id + "'></div>"
							}
						}
					},
					{
						field: 'seat',
						title: '位置',
						align: 'center',
						templet: function(p) {
							if(p.seat) {
								return "<div onclick=showDetail('" + p.id + "')>" + p.seat + "</div>";
							} else {
								return "<div></div>"
							}
						}
					},
					{
						field: 'numberNo',
						title: '编号',
						align: 'center',
						templet: function(p) {
							if(p.numberNo) {
								return "<div class='numberNo' onclick=showDetail('" + p.id + "')>" + p.numberNo + "</div><img class='img' src='" + url + "attachment/seekFile/" + p.attId + "' alt=''>";
							} else {
								return "<div></div>"
							}
						}
					},
					{
						field: 'risk',
						title: '作业风险',
						align: 'center',
						templet: function(p) {
							if(p.type == 1) {
								return "<div onclick=showDetail('" + p.id + "')>" + p.features + "</div>";
							} else {
								var v = '';
								var risks = JSON.parse(p.risk);
								if(risks != '' && risks.length > 0) {
									for(var i = 0; i < risks.length; i++) {
										v += risks[i].factor + ",";
									}
									return "<div onclick=showDetail('" + p.id + "')>" + v.substring(0, v.lastIndexOf(',')) + "</div>";
								}
								return "<div onclick=showDetail('" + p.id + "')>-</div>";
							}
						}

					}
				]
			],
			done: function(res, curr, count) {

			}
		});

	}
	getDangerList();

	//新增
	$(".addNews_btn").click(function() {
		$(".model").show();
	});

	//编辑
	$(".edit_btn").click(function() {
		var checkStatus = table.checkStatus('dangerListTable'),
			data = checkStatus.data,
			editId = "";

		if(data.length > 1) {
			layer.msg("只能选择一条数据");
			return;
		}

		if(data.length > 0) {
			editId = data[0].id;
			if(data[0].userId != salt) {
				layer.msg("只能编辑本人创建的信息");
				return;
			}
			if(data[0].type == 0) {
				location.href = '../addGM/add.html?id=' + editId;
			}
			if(data[0].type == 1) {
				location.href = '../addERR/add.html?id=' + editId;
			}
			if(data[0].type == 2) {
				location.href = '../addElement/add.html?id=' + editId;
			}

		} else {
			layer.msg("请选择需要编辑的数据");
		}
	});

	//批量删除
	$(".delAll_btn").click(function() {
		var deleteIdArr = [];
		$(".layui-table-box .layui-form-checked").each(function() {
			var id = $(this).parents("tr").find(".riskName").attr("riskid");
			id ? deleteIdArr.push(id) : '';
		})

		if(deleteIdArr.length > 0) {
			layer.confirm('确定删除选中的数据吗？', {
				icon: 3,
				title: '提示信息'
			}, function(index) {
				$.ajax({
					url: url + 'dangerList/del',
					dataType: 'json',
					async: false,
					type: "POST",
					data: {
						Token: salt,
						id: deleteIdArr.toString()
					},
					success: function(data) {
						if(data.code == 0) {
							layer.msg('删除成功');
						} else {
							layer.msg(data.msg);
						}

					},
					error: function(error) {
						console.log("获取失败");
					}
				});

				tableIns.reload();
				layer.close(index);
			})
		} else {
			layer.msg("请选择需要删除的数据");
		}
	});

	//导出
	$(".export_btn").click(function() {
		var checkStatus = table.checkStatus('dangerListTable'),
			data = checkStatus.data;
		if(data.length > 0) {
			var arr2 = new Array();
			var type = data[0].type;
			var typeName = data[0].typeName;
			var numberNo = data[0].numberNo;
			var entId = data[0].entId;
			var userId = data[0].userId;
			for(var i = 0; i < data.length; i++) {
				if(typeName != data[i].typeName || type != data[i].type || numberNo != data[i].numberNo || entId != data[i].entId || userId != data[i].userId) {
					layer.msg("单次只能导出基本信息相同的数据");
					return;
				}
				arr2.push(data[i].id);
			}
			$.post(url + 'dangerList/exportInfo', {
				Token: salt,
				ids: arr2.toString()
			}, function(result) {
				window.open(url + "file" + result.data);
			});
		} else {
			layer.msg("请选择需要导出的数据");
		}
	});
	//导入
	$(".import_btn").click(function() {
		layer.open({
			type: 2,
			title: false,
			content: "page/import2.html?url=dangerList",
			area: ['700px', '300px'],
			cancel: function(index, layero) {
				tableIns.reload();
			}
		});
	});

})

//弹框点击操作
$(".model .title .layui-tab-close").click(function() {
	$(".model").hide();
})
$(".model .button button").click(function() {
	$(".model").hide();
	var href = $(".model .content .active a").attr("mhref");
	if(href) {
		location.href = href;
	}

})
$(".model .content li").click(function() {
	$(this).toggleClass("active").siblings().removeClass("active");
})

function showDetail(checkId) {
	location.href = '../detail/detail.html?id=' + checkId;
}